<?php

error_reporting(E_ALL & ~E_NOTICE);
date_default_timezone_set('Asia/Ho_Chi_Minh');

session_start();

define('DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR);
include DIR . 'library/ChipVN/Loader.php';

\ChipVN\Loader::registerAutoLoad();


// fiter
$params = array('server', 'resize', 'watermark', 'logo');
foreach ($params as $param) {
    $name = $param . 'id';
    $data = intval($_REQUEST[$param]);
    if ($data < 0) {
        $data = 0;
    }
    ${$name} = $data;
}


##################### START CONFIG #######################

$sitename = 'chiplovebiz';
/**
 * Táº¡o vÃ  CHMOD folder nÃ y sang 777
 */
$tempdir = DIR . 'temp/';
$tempdir_thumb = DIR . 'temp/thumb/';
// danh sÃ¡ch logo
$logolist = array(
    1 => 'logo1.png',
    2 => 'logo2.png',
    3 => 'logo3.png',
);
// Náº¿u logo yÃªu cáº§u ko cÃ³ trong danh sÃ¡ch thÃ¬ dÃ¹ng logo1.png 
$default['logo'] = 'logo1.png';

// vá»‹ trÃ­ logo (right bottom, right center, right top, left top, .v.v.)
$logoPosition = 'rb';



// kÃ­ch cá»¡ resize
$resizelist = array(
    0 => 0, // ko resize
    1 => 100,
    2 => 150,
    3 => 320,
    4 => 640,
    5 => 800,
    6 => 1024
);
$default['resize'] = 800;


##################### END CONFIG #######################
$resizeid = @$_POST['resize'];


$watermark = $watermarkid > 0 ? TRUE : FALSE;

$logoPath = DIR . 'logo/' . (in_array($logoid, array_keys($logolist)) ? $logolist[$logoid] : $default['logo']);

$resizeWidth = $resizeid ? $resizeid : $default['resize'];


if ($_FILES['Filedata'] AND !$_FILES['Filedata']['error']) {

    $name = $_FILES['Filedata']['name'];
    if(!file_exists($tempdir.$name)) {
        $name = $name;
    } else {
        $name = genRandomString(10).$name;
    }
    uploadImg($_FILES['Filedata'], $tempdir,$name);
    copy($tempdir . $name, $tempdir_thumb = $tempdir_thumb . $name);
    $isUpload = TRUE;
} else if ($url = trim($_POST['url'])) {
    $isUpload = FALSE;
    \ChipVN\Image::leech($url, $imagePath = $tempdir . $sitename . date('dmY') . '.jpg');
}


// resize
if ($resizeWidth > 0) {
    \ChipVN\Image::resize($tempdir_thumb, $resizeWidth, 0);
}
// watermark
if ($watermark) {
    \ChipVN\Image::watermark($imagePath, $logoPath, $logoPosition);
}



if (file_exists($imagePath)) {
    //unlink($imagePath);
}

if ($isUpload) {
    echo 'image=' . $url;
} else {
    echo $url;
}

function uploadImg($FILES, $tempdir_thumb,$name='') {
    move_uploaded_file($FILES['tmp_name'], $tempdir_thumb . $name);
}


function genRandomString($length = 50) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters [rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}